# chat_processor.py
import openai
import asyncio

# chat_processor.py
from openai import AsyncOpenAI
from config.config import Config


class DeepSeekChat:
    """对话处理类"""

    def __init__(self, config):
        self.config = config
        self.messages = [{"role": "system", "content": config.SYSTEM_PROMPT}]
        self.client = AsyncOpenAI(
            api_key=config.DEEPSEEK_API_KEY,
            base_url="https://api.deepseek.com"
        )

    async def generate_reply(self, user_input):
        """生成AI回复 (异步流式处理)"""
        self.messages.append({"role": "user", "content": user_input})
        full_response = []

        try:
            # 使用新版API客户端
            response = await self.client.chat.completions.create(
                model="deepseek-chat",
                messages=self.messages,
                stream=True
            )

            print("小帕：", end="", flush=True)
            async for chunk in response:
                if content := chunk.choices[0].delta.content:
                    print(content, end="", flush=True)
                    full_response.append(content)

            assistant_response = "".join(full_response)
            self.messages.append({"role": "assistant", "content": assistant_response})
            return assistant_response

        except Exception as e:
            print("\nAPI请求失败:", str(e))
            return None